#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$


from basic_types.metric import Metric


__all__ = [ "MetricContainer" ]


class MetricContainer:
    '''container to store latest Metrics'''

    def __init__( self ):
        self.__data = {}

    def eq( self, metric1, metric2 ):
        "Equality operator must be defined in derived classes!"
        raise NotImplementedError, "subclasses of MetricContainer should provide an implementation of eq()"

    def get_key( self, metric ):
        '''build unique key for storing metric in container'''
        assert hasattr(metric, "source"), "attribute 'source' missing in metric"
        assert hasattr(metric, "name"), "attribute 'name' missing in metric"

        host = getattr(metric, "host", "")

        key = host + "." + metric.source + "." + metric.name

        return key

    def isNew( self, new_metric ):
        '''check if passed Metric is already in the container or contains updated data'''
        assert isinstance( new_metric, Metric ), "unsupported object type"

        key = self.get_key( new_metric )

        if not key in self.__data:
            #print "adding metric %s to container" % (key)
            self.__data[key] = new_metric
            return True
        else:
            #print "metric %s found in container, check" % (key)
            old_metric = self.__data[key]
            if self.eq(old_metric, new_metric):
                #print "still old metric", key
                return False
            else:
                self.__data[key] = new_metric
                #print "new metric", key
                return True

